package com.cloudcc.frame.trigger;

import com.cloudcc.deveditor.core.CCObject;
import com.cloudcc.deveditor.core.ServiceResult;
import com.cloudcc.deveditor.trigger.TriggerEditor;
import com.cloudcc.frame.comclass.ImportAccount;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;

public class Impdata extends TriggerEditor {
    /*
     * @Description:插入执行执行验证操作
     * 1获取相关变量与定义需要用到的相关变量
     * 2
     * 3
     * 4
     * 5
     * @T(n):
     * @Author: zxb
     * @Date:
     * @param null:
     * @return: null
     **/
    public void beforeinsert(){
        //城市名称
        String city=record_new.get("city")==null?"":record_new.get("city")+"";
        //区县名称
        String country=record_new.get("country")==null?"":record_new.get("country")+"";
        //省份名称
        String province=record_new.get("province")==null?"":record_new.get("province")+"";
        //管户经理的编号
        String khjl=record_new.get("khjl")==null?"":record_new.get("khjl")+"";
        //统一社会信用代码
        String code=record_new.get("code")==null?"":record_new.get("code")+"";
        //公共资源交易中心编号
        String psmc_num=record_new.get("psmc_num")==null?"":record_new.get("psmc_num")+"";
        //二级注册建造师人数
        String second_num=record_new.get("second_num")==null?"":record_new.get("second_num")+"";
        //企业性质
        String qyzx=record_new.get("qyzx")==null?"":record_new.get("qyzx")+"";
        //注册资本
        String zczb=record_new.get("zczb")==null?"":record_new.get("zczb")+"";
        //一级注册建造师人数
        String first_num=record_new.get("first_num")==null?"":record_new.get("first_num")+"";
        //注册地址
        String zcdz=record_new.get("zcdz")==null?"":record_new.get("zcdz")+"";
        //成立日期
        String clrq=record_new.get("clrq")==null?"":record_new.get("clrq")+"";
        //投标频次
        String tbpc=record_new.get("tbpc")==null?"":record_new.get("tbpc")+"";
        //法定代表人
        String fddbr=record_new.get("fddbr")==null?"":record_new.get("fddbr")+"";
        //客户名称
        String khmc=record_new.get("khmc")==null?"":record_new.get("khmc")+"";
        //主要投标工程类别
        String main_type=record_new.get("main_type")==null?"":record_new.get("main_type")+"";
        //主要投标区域
        String main_area=record_new.get("main_area")==null?"":record_new.get("main_area")+"";
        //工程资质数量
        String gczzsl=record_new.get("gczzsl")==null?"":record_new.get("gczzsl")+"";

        // 按社会统一信用代码查找
        String pattern_code = "[a-zA-Z0-9]{18}";
        //按数字查找
        String pattern_num = "^[0-9]*$";
        //按汉字查找
        String pattern_cn = "^[\\u4e00-\\u9fa5]{0,}$";
        //按日期格式查找
        String pattern_rq = "^\\d{4}[/|-]\\d{1,2}[/|-]\\d{1,2}";
        String Pattern2_rq = "^\\d{4}-\\d{1,2}-\\d{1,2}";
        // 创建 Pattern 对象
        java.util.regex.Pattern r = java.util.regex.Pattern.compile(pattern_code);
        java.util.regex.Pattern r1 = java.util.regex.Pattern.compile(pattern_num);
        java.util.regex.Pattern rq2 = java.util.regex.Pattern.compile(Pattern2_rq);
        java.util.regex.Pattern r3 = java.util.regex.Pattern.compile(pattern_rq);
        java.util.regex.Pattern r4 = java.util.regex.Pattern.compile(pattern_cn);


        // 现在创建 matcher 对象
        java.util.regex.Matcher m = r.matcher(code);
        java.util.regex.Matcher m1 = r1.matcher(first_num);
        java.util.regex.Matcher m2 = r1.matcher(second_num);
        java.util.regex.Matcher m3 = r1.matcher(zczb);
        java.util.regex.Matcher m4 = r1.matcher(gczzsl);
        java.util.regex.Matcher m5 = rq2.matcher(clrq);
        java.util.regex.Matcher m6 = r4.matcher(tbpc);
        java.util.regex.Matcher m12 = r3.matcher(clrq);
        if(!((code.length()==18&&m.find()))){
            if (true)trigger.addErrorMessage("请输入正确的统一社会信用代码");
        }

        //按数字查找
        if ("".equals(second_num)||(!m2.find())){
            if(true)trigger.addErrorMessage("二级注册建造师人数不能为空且只能是数字");
        }
        if ("".equals(first_num)||(!m1.find())){
            if(true)trigger.addErrorMessage("一级注册建造师人数不能为空且只能是数字");
        }
        if ("".equals(zczb)||(!m3.find())){
            if(true)trigger.addErrorMessage("注册资本不能为空且只能是数字");
        }
        if ("".equals(gczzsl)||(!m4.find())){
            if(true)trigger.addErrorMessage("工程资质数量不能为空且只能是数字");
        }

        //按汉字查找
        if ("".equals(qyzx)){
            if(true)trigger.addErrorMessage("企业性质不能为空");
        }
        if ("".equals(zcdz)){
            if(true)trigger.addErrorMessage("注册地址不能为空");
        }
        if ("".equals(tbpc)||(!m6.find())){
            if(true)trigger.addErrorMessage("请输入正确的投标频次（高频、中频、低频）");
        }
        if ("".equals(fddbr)){
            if(true)trigger.addErrorMessage("法定代表人不能为空");
        }
        if ("".equals(khmc)){
            if(true)trigger.addErrorMessage("客户名称不能为空");
        }
        if ("".equals(main_type)){
            if(true)trigger.addErrorMessage("主要投标工程类别不能为空");
        }
        if ("".equals(main_area)){
            if(true)trigger.addErrorMessage("主要投标区域不能为空");
        }
        //按日期查询
        if ("".equals(clrq)){
            if(true)trigger.addErrorMessage("成立日期不能为空");
        }
        if (m12.find()){
            try{
                SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
                SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sf.parse(clrq);
                clrq = sf2.format(date);
            }catch (Exception e){

            }
        }else {
            if(true)trigger.addErrorMessage("成立日期格式只能为xxxx-xx-xx或xxxx/xx/xx");
        }

        //用户id
        String userid="";
        //定义导入类
        ImportAccount importAccount = new ImportAccount(userInfo);
        net.sf.json.JSONObject check_json = new net.sf.json.JSONObject();
        //uuid
        String uid = UUID.randomUUID().toString();
        net.sf.json.JSONObject check_data = new net.sf.json.JSONObject();

        check_data.put("cusCertNo",code);
        String innerPlatformCode= "";
        String msg="线下保函系统已有该客户，导入失败";
        try {
            //获取公共资源交易中心id
            innerPlatformCode = importAccount.get_psmc(psmc_num);
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("CRM查询交易中心编码异常，请检查交易中心编码");
            e.printStackTrace();
        }
        //判空公共资源交易中心id
        if("".equals(innerPlatformCode)){
            if(true)trigger.addErrorMessage("CRM没有该资源交易中心编码，请检查交易中心编码");
        }

        check_data.put("innerPlatformCode",innerPlatformCode);
        check_json.put("invokeId",uid);
        check_json.put("data",check_data);
        Boolean offlineeleopp = false;
        try {
            //查询线下保函
            offlineeleopp = importAccount.offlineeleopp(check_json.toString());
            msg = importAccount.offlineeleopp_msg(check_json.toString());
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("线下保函系统查询异常，请检查社会信用统一代码");
            e.printStackTrace();
        }
        if(!offlineeleopp){
            if(true)trigger.addErrorMessage(msg);
        }
        Boolean is_have_role_incrm=false;
        try {
            //查询管户权限（统一社会信用代码，交易中心id）
            is_have_role_incrm=importAccount.is_have_role(code,innerPlatformCode);
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("CRM验证管护全失败，请联系管理员");
            e.printStackTrace();
        }
        //公共资源交易中心名称
        String psmc_name = "";
        if(is_have_role_incrm){
            String manage_group_sql = "select name from psmc " +
                    "where id='"+innerPlatformCode+"' " +
                    "and is_deleted='0'";
            List<CCObject> manage_group_list = this.cqlQuery("psmc", manage_group_sql);
            if (manage_group_list.size()>0){
                psmc_name = manage_group_list.get(0).get("name")==null?"":manage_group_list.get(0).get("name")+"";
            }
            if(true)trigger.addErrorMessage("客户在"+psmc_name+"已有管户经理，导入失败");
        }


        try {
            //获取所有人（客户经理）的用户id信息
            userid = importAccount.get_account_khjl(khjl);
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("查询该管户经理的员工编号失败，导入失败");
            e.printStackTrace();
        }

        if(userid.equals("")&&(!"".equals(khjl))){
            if(true)trigger.addErrorMessage("没有查询到该管户经理，导入失败");
        }
        Boolean is_have_role_incrmtoget=false;
        try {
            //查询管户权限（统一社会信用代码，交易中心id）
            is_have_role_incrmtoget=importAccount.is_have_roletoget(code,userid);
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("CRM验证管护全失败，请联系管理员");
            e.printStackTrace();
        }
        if(is_have_role_incrmtoget){
            if(true)trigger.addErrorMessage("CRM已存在该客户，并且管护权失效请去做拾取操作");
        }
        String city_id = "";
        String country_id = "";
        //查询城市的id
        String city_sql = "select id from city "+
                "where province='"+province+"' "+
                "and name='"+city+"' "+
                "and is_deleted='0' ";
        List<CCObject> city_list = this.cqlQuery("city", city_sql);
        if (city_list.size()>0){
            city_id = city_list.get(0).get("id") == null ? "" : city_list.get(0).get("id") + "";
        }
        if("".equals(city_id)){
            if(true)trigger.addErrorMessage("没有在CRM查询该城市的名称，请检查城市或者省份名称是否一致");
        }
        //查询区县的id
        String country_sql = "select id from country "+
                "where city='"+city_id+"' " +
                "and name='"+country+"' " +
                "and is_deleted='0'";
        List<CCObject> country_list = this.cqlQuery("country", country_sql);
        if (country_list.size()>0){
            country_id = country_list.get(0).get("id")==null?"":country_list.get(0).get("id")+"";
        }
        if("".equals(country_id)){
            if(true)trigger.addErrorMessage("没有在CRM查询该区县的名称，请检查城市或者区县名称是否一致");
        }

    }
    /*
     * @Description:插入导入电子保函客户数据，执行插入操作
     * @T(n):
     * @Author: zxb
     * @Date:
     * @param null:
     * @return: null
     **/
    public void afterinsert(){
        //管户状态
         String ghzt_continue = "未生效";
        //正式环境客户记录类型
        //private String jllx = "202385551266A597FF1B";

        //测试环境客户记录类型
         String jllx = "20211C59581DC5CZOn5N";
        //状态待分配
         String account_dfp = "待分配";
        //状态待跟进
         String account_dgj = "待跟进";
        //客户开函状态
        String deal_status = "未开函";
        //城市
        String city=record_new.get("city")==null?"":record_new.get("city")+"";
        //二级注册建造师人数
        String second_num=record_new.get("second_num")==null?"":record_new.get("second_num")+"";
        //区县
        String country=record_new.get("country")==null?"":record_new.get("country")+"";
        //企业性质
        String qyzx=record_new.get("qyzx")==null?"":record_new.get("qyzx")+"";
        //省份
        String province=record_new.get("province")==null?"":record_new.get("province")+"";
        //注册资本
        String zczb=record_new.get("zczb")==null?"":record_new.get("zczb")+"";
        //一级注册建造师人数
        String first_num=record_new.get("first_num")==null?"":record_new.get("first_num")+"";
        //客户经理
        String khjl=record_new.get("khjl")==null?"":record_new.get("khjl")+"";
        //注册地址
        String zcdz=record_new.get("zcdz")==null?"":record_new.get("zcdz")+"";
        //所属圈层
        String ssqc=record_new.get("ssqc")==null?"":record_new.get("ssqc")+"";
        //统一社会信用代码
        String code=record_new.get("code")==null?"":record_new.get("code")+"";
        //成立日期
        String clrq=record_new.get("clrq")==null?"":record_new.get("clrq")+"";
        //投标频次
        String tbpc=record_new.get("tbpc")==null?"":record_new.get("tbpc")+"";
        //法定代表人
        String fddbr=record_new.get("fddbr")==null?"":record_new.get("fddbr")+"";
        //公共资源交易中心
        String psmc_num=record_new.get("psmc_num")==null?"":record_new.get("psmc_num")+"";
        //客户名称
        String khmc=record_new.get("khmc")==null?"":record_new.get("khmc")+"";
        //主要投标工程类别
        String main_type=record_new.get("main_type")==null?"":record_new.get("main_type")+"";
        //主要投标区域
        String main_area=record_new.get("main_area")==null?"":record_new.get("main_area")+"";
        //工程资质数量
        String gczzsl=record_new.get("gczzsl")==null?"":record_new.get("gczzsl")+"";
        ImportAccount importAccount = new ImportAccount(userInfo);
        CCObject account = new CCObject("Account");
        String city_id = "";
        String country_id = "";
        String userid="";
        String psmc_id="";
        String ele_open_info_id = "";
        String ele_num_id = "";
        try {
            //获取公共交易资源中心的id
            psmc_id=importAccount.get_psmc(psmc_num);
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("CRM查询交易中心编码异常，请检查交易中心编码");
            e.printStackTrace();
        }

        boolean is_have=false;
        try {
            //查询验证客户是否存在
            is_have= importAccount.find_account(code);
        } catch (Exception e) {
            if(true)trigger.addErrorMessage("CRM查询客户存在异常");
            e.printStackTrace();
        }

        //查询城市的id
        String city_sql = "select id from city "+
                "where province='"+province+"' "+
                "and name='"+city+"' "+
                "and is_deleted='0' ";
        List<CCObject> city_list = this.cqlQuery("city", city_sql);
        if (city_list.size()>0){
            city_id = city_list.get(0).get("id") == null ? "" : city_list.get(0).get("id") + "";
        }
        //查询区县的id
        String country_sql = "select id from country "+
                "where city='"+city_id+"' " +
                "and name='"+country+"' " +
                "and is_deleted='0'";
        List<CCObject> country_list = this.cqlQuery("country", country_sql);
        if (country_list.size()>0){
            country_id = country_list.get(0).get("id")==null?"":country_list.get(0).get("id")+"";
        }
        account.put("name", khmc);
        account.put("invoiceTaxNo", code);
        account.put("province", province);
        account.put("fk_city_name", city_id);
        account.put("fk_country_name", country_id);
        account.put("registeredAddress", zcdz);
        account.put("full_name", fddbr);
        account.put("registered_capital", zczb);
        account.put("qyxz", qyzx);
        account.put("establishDate", clrq);
        //开函状态
        account.put("deal_status",deal_status);
        //记录类型
        account.put("recordtype", jllx);
        //客户在CRM存在的情况
        if(is_have){
            //肯定填写管户经理
            if(!khjl.equals("")){
                account.put("follow_status", account_dgj);
                try {
                    //获取所有人（客户经理）的用户id信息
                    userid=importAccount.get_account_khjl(khjl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                    account.put("ownerid", userid);
                    //根据统一社会信用代码查存在的客户
                    List<CCObject> hava_account = this.cquery("Account", "invoiceTaxNo='" + code + "'");
                    String fk_account="";
                    if(hava_account.size()>0){
                        //获得存在客户的id
                        fk_account= hava_account.get(0).get("id")==null?"":hava_account.get(0).get("id")+"";
                        account.put("id",fk_account);
                        this.update(account);
                    }
                try {
                    //插入管户小组（客户存在is_shared:是）共享
                    importAccount.insert_manage_group("是",userid,
                            psmc_id,fk_account,ghzt_continue,
                            code,province,zcdz,city_id,country_id);
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("CRM插入管护小组出现异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
                try {
                    String ele_open_info_sql = "select id from ele_open_info " +
                            "where fk_account='"+fk_account+"' " +
                            "and is_deleted='0'";
                    List<CCObject> ele_open_info_list = this.cqlQuery("ele_open_info", ele_open_info_sql);
                    if (ele_open_info_list.size()>0){
                        ele_open_info_id = ele_open_info_list.get(0).get("id")==null?"":ele_open_info_list.get(0).get("id")+"";
                    }
                    //更新公招信息
                    importAccount.update_ele_open_info(ele_open_info_id,fk_account,first_num,second_num,gczzsl,main_type,
                            main_area,ssqc);
                }catch (Exception e){
                    if(true)trigger.addErrorMessage("CRM更新公招信息出现异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
                String ele_num_sql = "select id from ele_num " +
                        "where fk_psmc='"+psmc_id+"' " +
                        "and fk_account='"+fk_account+"' " +
                        "and is_deleted='0'";
                try {
                    List<CCObject> ele_num_list = this.cqlQuery("ele_num", ele_num_sql);
                    if (ele_num_list.size()>0){
                        ele_num_id = ele_num_list.get(0).get("id")==null?"":ele_num_list.get(0).get("id")+"";
                        //更新投标频率信息
                        importAccount.update_ele_num(ele_num_id,tbpc,fk_account,psmc_id);
                    }else{
                        CCObject ele_num = new CCObject("ele_num");
                        ele_num.put("frequece",tbpc);
                        ele_num.put("fk_psmc",psmc_id);
                        ele_num.put("fk_account",fk_account);
                        ServiceResult insert_ele_num = this.insert(ele_num);
                        ele_num_id=insert_ele_num.get("id")+"";
                    }

                }catch (Exception e){

                    if(true)trigger.addErrorMessage("CRM更新投标频率出现异常，请联系管理员"+e.toString()+ele_num_sql);
                    e.printStackTrace();
                }
            }else{
                if(true)trigger.addErrorMessage("该客户已存在，请去公海池分配！导入失败");
            }
        }else{
            //客户在CRM系统不存在的情况
            if(!khjl.equals("")){
                //填写了管户经理的，管户小组是‘否’,不单独共享
                try {
                    ////获取所有人（客户经理）的用户id信息
                    userid=importAccount.get_account_khjl(khjl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                account.put("follow_status", account_dgj);
                account.put("ownerid", userid);
                ServiceResult insert = this.insert(account);
                String fk_account=insert.get("id")+"";
                try {
                    //插入管户小组（客户不存在is_shared:否）不单独共享
                    importAccount.insert_manage_group("否",userid,
                            psmc_id,fk_account,ghzt_continue,
                            code,province,zcdz,city_id,country_id);
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("CRM插入管护小组出现异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
                try {
                    //插入公招信息
                    importAccount.insert_ele_open_info(fk_account,first_num,
                            second_num,gczzsl,main_type,main_area,ssqc);
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("插入公招信息异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
                try {
                    //插入投标频率
                    importAccount.insert_ele_num(tbpc,fk_account,psmc_id);
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("插入投标频率信息异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
            }else{
                //所有人没填写分配给谁的，不插入管户小组，其他信息正常保存
                try {
                    userid=importAccount.get_pool_id();
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("获取用户绑定公海池id失败，导入失败"+e.toString());
                    e.printStackTrace();
                }
                account.put("follow_status", account_dfp);
                account.put("ownerid", userid);
                ServiceResult insert = this.insert(account);
                String fk_account=insert.get("id")+"";
                //插入公招信息
                try {
                    importAccount.insert_ele_open_info(fk_account,first_num,
                            second_num,gczzsl,main_type,main_area,ssqc);
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("插入公招信息异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
                //插入投标频率
                try {
                    importAccount.insert_ele_num(tbpc,fk_account,psmc_id);
                } catch (Exception e) {
                    if(true)trigger.addErrorMessage("插入投标频率信息异常，请联系管理员"+e.toString());
                    e.printStackTrace();
                }
            }
        }
    }

}
